package net.zjitc.utils.db;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import sun.awt.AWTAccessor;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/11/9.
 */
public class C3P0Utils {
    public static ComboPooledDataSource ds = null;
    public static ThreadLocal<Connection> th = new ThreadLocal<Connection>();
    static {
        ds = new ComboPooledDataSource();
    }
    public static ComboPooledDataSource getDataSource(){
        return ds;
    }
    public static Connection getConnection() throws SQLException {
        Connection conn = th.get();
        if(conn != null){
            return conn;//带事务的连接
        }
        return ds.getConnection();//此连接不带事务
    }
    //开启一个事务
    public static void startTransation(){
        try {
            Connection conn = th.get();
            if(conn != null){
                throw new RuntimeException("事务已经开启，不需要再开启");
            }
            conn = ds.getConnection();
            th.set(conn);
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //提交事务
    public static void commitTransation() throws SQLException {
        Connection conn = th.get();
        if(conn != null){
            throw new RuntimeException("本身没有事务，无法提交");
        }
        conn.commit();
        conn.close();
        conn = null;
        th.remove();
    }
    //回滚
    public static void rollbackTransation() throws SQLException {
        Connection conn = th.get();
        if(conn != null){
            throw new RuntimeException("本身没有事务，无法回滚");
        }
        conn.rollback();
        conn.close();
        conn = null;
        th.remove();
    }
    //关闭
    public static void closeConnection(Connection connection) throws SQLException {
        Connection conn = th.get();
        if(conn != connection){//只关闭普通的连接，带事务的连接在提交或回滚的时候关闭
            connection.close();
        }
    }

}
